package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

func ShareStudent(c *gin.Context) {
	db := getDBConnection()
	defer db.Close()

	var student Student
	if err := c.BindJSON(&student); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid input"})
		return
	}

	// 使用student对象中的值生成分享链接
	shareUrl := fmt.Sprintf("http://%s/share?name=%s&chinese=%d&math=%d&english=%d",
		c.Request.Host, student.Name, student.Chinese, student.Math, student.English)

	// 插入到数据库
	query := "INSERT INTO share (name, link) VALUES (?, ?)"
	_, err := db.Exec(query, student.Name, shareUrl)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to insert data"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Share created successfully"})
}

func ShareStudent1(c *gin.Context) {
	name := c.Query("name")
	chinese := c.Query("chinese")
	math := c.Query("math")
	english := c.Query("english")

	c.HTML(http.StatusOK, "share.html", gin.H{
		"Name":    name,
		"Chinese": chinese,
		"Math":    math,
		"English": english,
	})
}

func ShowShares(c *gin.Context) {
	db := getDBConnection()
	defer db.Close()

	rows, err := db.Query("SELECT id, name, link FROM share")
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch data"})
		return
	}
	defer rows.Close()

	var shares []Share
	for rows.Next() {
		var share Share
		if err := rows.Scan(&share.ID, &share.Name, &share.Link); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to scan data"})
			return
		}
		shares = append(shares, share)
	}

	if err := rows.Err(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Row error"})
		return
	}

	c.HTML(http.StatusOK, "share_list.html", gin.H{
		"title":  "我的分享",
		"shares": shares,
	})
}

func deleteShareHandler(c *gin.Context) {
	log.Println("deleteShareHandler called")

	db := getDBConnection()
	defer db.Close()

	var share Share
	if err := c.ShouldBindJSON(&share); err != nil {
		log.Println("Invalid share data:", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid share data"})
		return
	}
	_, err := db.Exec("DELETE FROM share WHERE id = ?", share.ID)
	if err != nil {
		log.Println("Error deleting share:", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Share deleted successfully"})
}
